/**
 * Auto gen via dbpojo-gen.
 */
package com.us.usws.site.ipodium.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import net.iwsh.core.utils.ObjectUtils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.us.usws.biz.ResourceStorageReplacer;
import com.us.usws.common.CommonUtils;
import com.us.usws.common.SiteConstants;
import com.us.usws.model.domain.base.BaseDict;
import com.us.usws.model.domain.base.BaseVideoCat;
import com.us.usws.model.domain.base.VideoTypeExtattr;
import com.us.usws.model.domain.video.Video;
import com.us.usws.model.domain.video.VideoFile;
import com.us.usws.service.cud.VideoCUDService;
import com.us.usws.service.ro.BaseVideoCatROService;
import com.us.usws.service.ro.VideoROService;
import com.us.usws.site.ipodium.vo.VideoUploadVO;
import com.us.usws.support.ext.CacheManager;
import com.us.usws.support.uitls.SiteWebContext;

/**
 * Struts2 action
 * @author robot
 */
public class AddVideoAction extends ActionSupport {

	private static Log log = LogFactory.getFactory().getInstance(AddVideoAction.class);

	private static final long serialVersionUID = 1L;

	@Inject
	private BaseVideoCatROService catS;

	@Inject
	private VideoROService vS;

	@Inject
	private VideoCUDService vcudS;

	private int selectedTypeDsid;
	private String selectedCatUid;

	private List<BaseDict> videoTypes = CacheManager.getDictCache().getDicts(SiteConstants.DICT_DOMAIN_VIDEO_TYPE);
	private List<BaseVideoCat> rltVideoCats;

	private List<VideoTypeExtattr> extattrs;

	/**
	 * for commit
	 */
	private Map<String, String> recvals = new HashMap<String, String>();
	private VideoUploadVO vo = new VideoUploadVO();

	/**
	 * prepare
	 */
	private void prepare() {
		rltVideoCats = CacheManager.getVideoCatCache().getCatsByVideoTypeDsid(selectedTypeDsid);
		if (StringUtils.isNotBlank(selectedCatUid)) {
			String catCN = CacheManager.getVideoCatCache().getCatName(selectedCatUid);
			String videoTypeCN = CacheManager.getDictCache().getDictNameBySepId(SiteConstants.DICT_DOMAIN_VIDEO_TYPE, selectedTypeDsid);
			vo.setCatCN(catCN);
			vo.setVideoTypeCN(videoTypeCN);
			vo.setTypeDsid(selectedTypeDsid);
			vo.setCatUid(selectedCatUid);
			log.info("now we have selectedTypeDsid: [" + selectedTypeDsid + "]=[" + videoTypeCN + "], selectedCatUid: [" + selectedCatUid
					+ "]=[" + catCN + "].");

			extattrs = CacheManager.getVideoTypeExtattrCache().getVideoTypeExtattrs(selectedTypeDsid);
		}
	}

	/**
	 * init method
	 * @return
	 */
	public String init() {
		prepare();

		if (vo.getCatCN() != null && vo.getVideoTypeCN() != null) {
			return SUCCESS;

		}

		return INPUT;
	}

	public String commit() {
		log.info("Now commit!");
		prepare();

		if (StringUtils.isBlank(vo.getSnapshotPath()) || StringUtils.isBlank(vo.getVideoPath())) {
			log.warn("No file uploaded.");
			return INPUT;
		}
		log.info(ObjectUtils.toXML(vo));

		SiteWebContext swc = new SiteWebContext(ServletActionContext.getRequest(), null);
		String userUid = swc.getIpodiumUser().getUid();
		Date now = new Date();
		//to save
		int seqNum = vS.getTotalCount() + 1;
		Video video = new Video();
		video.setName(vo.getTitle());
		video.setTypeSid(vo.getTypeDsid());
		video.setTags(vo.getTags());

		video.setAuthStatusDsid(SiteConstants.VIDEO_AUTH_STATUS_PENDING);
		video.setSeqNum(seqNum);
		video.setCreateByUid(userUid);
		video.setCreateDate(now);

		video.setDescription(vo.getDescriptoin());
		video.setCatUids(new String[] { vo.getCatUid() });

		//video file
		VideoFile vf = new VideoFile();
		vf.setCreateByUid(userUid);
		vf.setCreateDate(now);
		String filePath = vo.getVideoPath();
		int pos = filePath.lastIndexOf('.');
		String ext = filePath.substring(pos + 1);
		vf.setFileExt(ext);

		String tmpPath = ResourceStorageReplacer.getUserTmpDir(userUid);
		tmpPath += "/" + filePath;
		long fileSize = FileUtils.sizeOf(new File(tmpPath));
		vf.setFileSize(fileSize);

		vf.setMimeType(CommonUtils.getMimeType(ext.toLowerCase()));
		vf.setOrigFileName(filePath);
		vf.setSnapshot(vo.getSnapshotPath());
		vcudS.addVideoFromTmp(video, vf);
		return SUCCESS;
	}

	/**
	 * load related cats for ajax
	 */
	public void ajaxLoadRlt() {
		rltVideoCats = CacheManager.getVideoCatCache().getCatsByVideoTypeDsid(selectedTypeDsid);

		ServletActionContext.getResponse().setContentType("text/plain");
		for (int i = 0; i < rltVideoCats.size(); i++) {
			BaseVideoCat each = rltVideoCats.get(i);
			StringBuilder sb = new StringBuilder();
			sb.append("<option value=\"").append(each.getUid()).append("\"");
			if (i == 0) {
				sb.append(" selected=\"selected\"");
			}
			sb.append(">").append(each.getName()).append("</option>");
			getOut().println(sb.toString());
		}
		getOut().flush();
	}

	public int getSelectedTypeDsid() {
		return selectedTypeDsid;
	}

	public void setSelectedTypeDsid(int selectedTypeDsid) {
		this.selectedTypeDsid = selectedTypeDsid;
	}

	public List<BaseDict> getVideoTypes() {
		return videoTypes;
	}

	public void setVideoTypes(List<BaseDict> videoTypes) {
		this.videoTypes = videoTypes;
	}

	public List<BaseVideoCat> getRltVideoCats() {
		return rltVideoCats;
	}

	public void setRltVideoCats(List<BaseVideoCat> rltVideoCats) {
		this.rltVideoCats = rltVideoCats;
	}

	public PrintWriter getOut() {
		HttpServletResponse res = ServletActionContext.getResponse();
		PrintWriter out = null;
		if (res != null) {
			try {
				out = res.getWriter();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return out;
	}

	public String getSelectedCatUid() {
		return selectedCatUid;
	}

	public void setSelectedCatUid(String selectedCatUid) {
		this.selectedCatUid = selectedCatUid;
	}

	public BaseVideoCatROService getCatS() {
		return catS;
	}

	public void setCatS(BaseVideoCatROService catS) {
		this.catS = catS;
	}

	public List<VideoTypeExtattr> getExtattrs() {
		return extattrs;
	}

	public void setExtattrs(List<VideoTypeExtattr> extattrs) {
		this.extattrs = extattrs;
	}

	public Map<String, String> getRecvals() {
		return recvals;
	}

	public void setRecvals(Map<String, String> recvals) {
		this.recvals = recvals;
	}

	public VideoUploadVO getVo() {
		return vo;
	}

	public void setVo(VideoUploadVO vo) {
		this.vo = vo;
	}

}